<?php 
class User_setting extends MY_Controller {
	function __construct() {
		parent::__construct();
		$this->load->model('user_model', '', true);
		$this->load->model('admin_model', '', true);
	}
	
	function user_setting_form() {
		$data['user_data'] = $this->user_model->get_by_id($_SESSION['id']);
		$data['admin_data'] = $this->admin_model->_get_by_foreign_id($_SESSION['id']);
		
		$this->load->view('admin/user_setting/main', $data);
	}
	
	function user_setting_submit() {
		$user_setting_array = $this->input->post("user_setting_array");
		$user_data['id'] = $_SESSION['id'];
		
		foreach ($user_setting_array as $v) {
			if ($v[0] == 'email') {
				$user_data[$v[0]] = $v[1];
			} else {
				$admin_data[$v[0]] = $v[1];
			}
		}
		
		/*echo "<pre>";
		print_r($user_data);
		print_r($admin_data);
		return ;*/
		$this->user_model->update($user_data);
		$this->admin_model->update_by_foreign_id($_SESSION['id'], $admin_data);
		$this->output->set_output(json_encode("succeed"));
	}
	
	function user_change_pwd() {
		$old_pwd = $this->input->post("old_pwd");
		$pwd = $this->input->post("pwd");
		$re_pwd = $this->input->post("re_pwd");
		
		if ($old_pwd == '') {
			$this->output->set_output(json_encode('null_old_password_error'));
			return FALSE;
        } elseif (mb_strlen($old_pwd) > 10 OR mb_strlen($old_pwd) < 4) {
        	$this->output->set_output(json_encode('old_password_length_error'));
	        return FALSE;
        }
	        
		if ($pwd == '') {
			$this->output->set_output(json_encode('null_new_password_error'));
			return FALSE;
        } elseif (mb_strlen($pwd) > 10 OR mb_strlen($pwd) < 4) {
        	$this->output->set_output(json_encode('new_password_length_error'));
	        return FALSE;
        }
	        
		if ($re_pwd == '') {
			$this->output->set_output(json_encode('null_re_password_error'));
			return FALSE;
        } elseif (mb_strlen($re_pwd) > 10 OR mb_strlen($re_pwd) < 4) {
        	$this->output->set_output(json_encode('re_password_length_error'));
	        return FALSE;
        }
		
		if ($pwd != $re_pwd) {
			$this->output->set_output(json_encode('conf_password_match_error'));
			return FALSE;
		}
		
		if ($old_pwd == $this->user_model->get_by_id($_SESSION['id'], 'password')) {
			$user_data['id'] = $_SESSION['id'];
			$user_data['password'] = $pwd;
			$this->user_model->update($user_data);
			$this->output->set_output(json_encode('succeed'));
		} else {
			$this->output->set_output(json_encode('old_password_match_error'));
			return FALSE;
		}
	}
}